package com.zhang.simple.chatgpt;

import io.netty.channel.*;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.InetSocketAddress;

/**
 * description
 *
 * @author zhangFanJun
 * @date 2024-02-27 15:00
 **/
@Slf4j
@ChannelHandler.Sharable
@Component
public class WebSocketInBoundHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Resource
    private ChatService chatService;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        ChannelId channelId = channel.id();
        ChannelHold.CONNECTION.put(channelId, channel);
        String remoteIp = ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress();

    }

    /**
     * 注意这个时候发送消息不能用channelActive，这个只执行一次，并且在通道完成的时候执行
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {

        String receivedMessage = msg.text();
        log.info("=====》收到消息：{}", receivedMessage);

        chatService.read(ctx, receivedMessage);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

        log.error("出现异常：", cause);
        cause.printStackTrace();

        ctx.close();
    }
}
